<template>
  <!-- 表格 -->
  <div>
    <!-- 支持下拉刷新 -->
    <van-pull-refresh v-model="loading" @refresh="refresh">
      <!-- 支持上拉懒加载 -->
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :immediate-check="false"
        :finished-text="tableData.length ? '没有更多了' : ''"
        :offset="pager.size"
        @load="onLoad"
      >
        <!-- 列表数据 -->
        <vxe-table
          v-show="tableData.length || !loading"
          border="inner"
          size="mini"
          :data="tableData"
          :header-cell-style="{ 'text-align': 'left' }"
          :cell-style="{ 'text-align': 'left' }"
        >
          <vxe-column type="seq" width="35"></vxe-column>
          <template v-for="col of tableColumns">
            <!-- 自定义显示 -->
            <vxe-column
              v-if="col['type'] === 'custom'"
              :key="col['field']"
              :field="col['field']"
              :title="col['label']"
              :width="col['width']"
            >
              <template #default="{ row, rowIndex }">
                <span
                  v-html="col.formatValue(row, rowIndex, activeNames, doneType)"
                ></span>
              </template>
            </vxe-column>
            <!-- 链接 -->
            <vxe-column
              v-else-if="col['type'] === 'link'"
              :key="col['field']"
              :field="col['field']"
              :title="col['label']"
              :width="col['width']"
            >
              <template #default="{ row }">
                <a @click.stop="handleTodo(row)">{{ row[col['field']] }}</a>
              </template>
            </vxe-column>
            <!-- 按钮 -->
            <vxe-column
              v-else-if="col['type'] === 'btn'"
              :key="col['field']"
              :field="col['field']"
              :title="col['label']"
              :width="col['width']"
            >
              <template #default="{ row }">
                <a v-if="handleText" @click.stop="handleTodo(row)">{{
                  handleText
                }}</a>
              </template>
            </vxe-column>
            <!-- 预警等级 -->
            <vxe-column
              v-else-if="col['type'] === 'warnLevel'"
              :key="col['field']"
              :field="col['field']"
              :title="col['label']"
              :width="col['width']"
            >
              <template #default="{ row }">
                <span>{{
                  (levelOptions.find((r) => r['value'] == row[col['field']]) ||
                    {})['name'] || ''
                }}</span>
              </template>
            </vxe-column>
            <vxe-column
              v-else
              :key="col['field']"
              :field="col['field']"
              :title="col['label']"
              :width="col['width']"
            >
            </vxe-column>
          </template>
        </vxe-table>
      </van-list>
    </van-pull-refresh>
    <HandlePop
      v-if="curHandleData"
      ref="refHandlePop"
      :all-grade-info="allGradeInfo"
      @close="closePop"
      @submitSuccess="submitSuccess"
    ></HandlePop>
  </div>
</template>
<script lang="ts">
import HandlePop from './handlePop/index.vue'
import { deepClone } from '/@/util/util.js'
import { useRouter } from 'vue-router'
import { useStore } from '/@/store'
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  nextTick,
  computed,
} from 'vue'
import { refreshTodoData, toEvaluation } from '/@/util/business-util'
import { getTodoDetails, getColumns } from './config'

export default defineComponent({
  components: { HandlePop },
  props: {
    activeNames: String, // 待办类型
    doneType: String, // 完成状态
    option: Object, // 当前配置
    userInfo: Object, // 当前用户信息
    conditionOp: Object, // 条件
    handleText: String, // 按钮名称
    allGradeInfo: Array, // 所有年级
  },
  setup(props, _context) {
    const router = useRouter()
    const { commit, state } = useStore()
    const refHandlePop: any = ref(null) // 同vue2中refs的handlePop
    const loading: any = ref(false)
    const activeNames = props.activeNames
    const doneType = props.doneType
    const option = props.option
    const userInfo = props.userInfo
    const handleText = props.handleText
    const allGradeInfo = props.allGradeInfo
    let conditionOp = props.conditionOp
    const finished: any = ref(false)
    let tableData: any = ref([])
    let tableColumns: any = ref([])
    // 分页信息
    let pager = reactive({
      current: 1,
      size: 20,
    })
    let curHandleData: any = ref(null) // 当前处理的待办数据
    const levelOptions = computed(() => state.levelOptions) // 所有预警级别
    onMounted(async () => {
      //创建组件时，加载第1页数据
      refresh()
    })
    function refresh() {
      reload(null)
    }
    // 重新加载数据（外部组件调用）
    async function reload(condOp: any) {
      conditionOp = condOp || conditionOp
      pager.current = 1
      _context.emit('refreshTodoTotal') // 刷新数量
      loading.value = true // 显示loading
      await refreshTodoDetails()
      loading.value = false // 隐藏loading
    }
    // 根据待办类型，刷新对应待办详情
    async function refreshTodoDetails() {
      // 根据待办类型、已完成状态等查询对应的待办详情数据
      let data: any = await getTodoDetails(
        commit,
        state,
        activeNames,
        conditionOp,
        doneType,
        pager
      )
      if (pager.current === 1) {
        tableData.value = []
      }
      // 需要显示的数据
      tableData.value = tableData.value.concat((data && data.data) || [])
      let total = (data && data.total) || 0
      finished.value = pager.current * pager.size >= total // 是否没有数据了
      // 需要显示的字段
      tableColumns.value = getColumns(userInfo, activeNames, doneType)
      console.log(
        '单个类型的待办内容',
        activeNames,
        tableData.value,
        tableColumns.value,
        conditionOp,
        doneType
      )
      return tableData.value
    }
    async function handleTodo(rowData: any) {
      curHandleData.value = {
        activeNames: activeNames,
        rowData: rowData,
      }
      // 测评
      if (activeNames === 'evaluation') {
        // 去测评
        toEvaluation(rowData, router, state, doneType === 'undone', true)
      } else {
        nextTick(() => {
          refHandlePop.value.show(activeNames, rowData, doneType === 'undone')
        })
      }
    }
    // 待办处理成功之后的回调
    async function submitSuccess() {
      let curData = deepClone(curHandleData.value)
      refreshTodoData(commit, userInfo) // 刷新待办事项数量
      refreshTodoDetails() // 根据待办类型，刷新对应待办详情
    }
    return {
      refHandlePop,
      loading,
      tableData,
      tableColumns,
      activeNames, // 待办类型
      doneType,
      option, // 当前配置
      userInfo, // 当前用户信息
      conditionOp, // 条件
      pager,
      handleText, // 按钮名称
      allGradeInfo,
      levelOptions,
      curHandleData,
      finished,
      refresh,
      reload,
      handleTodo, // 去处理
      submitSuccess,
      // 注意：如果一屏全部展示完了，就不会触发该方法
      async onLoad() {
        pager.current += 1
        loading.value = true // 显示loading
        await refreshTodoDetails()
        loading.value = false // 隐藏loading
      },
      closePop() {
        // 之所以使用nextTick延迟销毁，submitSuccess需要使用到
        nextTick(() => {
          curHandleData.value = null
        })
      },
    }
  },
})
</script>

<style lang="less" scoped>
@import '/@/styles/index.less';
/deep/ .vxe-cell {
  padding: 0 4px;
  user-select: auto;
}
a {
  color: @theme-color;
}
</style>
